// import legacyPlugin from '@vitejs/plugin-legacy'
import { viteLogo } from './src/core/config'
// import Banner from 'vite-plugin-banner'
import * as path from 'path'
import * as dotenv from 'dotenv'
import * as fs from 'fs'
import vuePlugin from '@vitejs/plugin-vue'
import viteCompression from 'vite-plugin-compression'
import { visualizer } from 'rollup-plugin-visualizer'
export default ({
  command,
  mode
}) => {
  const models = [
    {
      name: 'pre',
      str: 'pre'
    },
    {
      name: 'mm',
      str: 'mm'
    },
    {
      name: 'dev',
      str: 'development'
    },
    {
      name: 'build',
      str: 'production'
    },
    {
      name: 'build:dev',
      str: 'development'
    },
    {
      name: 'build:mm',
      str: 'mm'
    }
  ]
  const res = models.filter(item => {
    return item.name == process.env.npm_lifecycle_event
  })
  console.log(res);
  const NODE_ENV = res[0].str
  const envFiles = [
    `.env.${NODE_ENV}`
  ]
  for (const file of envFiles) {
    const envConfig = dotenv.parse(fs.readFileSync(file))
    for (const k in envConfig) {
      process.env[k] = envConfig[k]
    }
  }

  viteLogo(process.env)

  // const timestamp = Date.parse(new Date())

  const optimizeDeps = {}

  const alias = {
    '@': path.resolve(__dirname, './src'),
    'vue$': 'vue/dist/vue.runtime.esm-bundler.js',
  }

  const esbuild = {}

  return {
    base: './', // index.html文件所在位置
    root: './', // js导入的资源路径，src
    resolve: {
      alias,
    },
    define: {
      'process.env': {}
    },
    server: {
      // 如果使用docker-compose开发模式，设置为false
      open: true,
      port: process.env.VITE_CLI_PORT,
      proxy: {
        // 把key的路径代理到target位置
        // detail: https://cli.vuejs.org/config/#devserver-proxy
        [process.env.VITE_BASE_API]: { // 需要代理的路径   例如 '/api'
          target: `${process.env.VITE_BASE_PATH}:${process.env.VITE_SERVER_PORT}/`, // 代理到 目标路径
          changeOrigin: true,
          rewrite: path => path.replace(new RegExp('^' + process.env.VITE_BASE_API), ''),
        }
        // '/api/biz': {
        //   target: 'http://10.1.55.46:8482',
        //   changeOrigin: true,
        //   rewrite: path => path.replace(new RegExp('^' + '/api/biz'), ''),
        // },
        // '/api/basic': {
        //   target: 'http://10.1.55.46:8481',
        //   changeOrigin: true,
        //   rewrite: path => path.replace(new RegExp('^' + '/api/basic'), ''),
        // },
      },
    },
    build: {
      target: 'es2017',
      minify: 'terser', // 是否进行压缩,boolean | 'terser' | 'esbuild',默认使用terser
      manifest: false, // 是否产出manifest.json
      sourcemap: false, // 是否产出sourcemap.json
      outDir: 'dist', // 产出目录
      emptyOutDir: true,
      cssCodeSplit: true,
      brotliSize: false, //启用/禁用 brotli 压缩大小报告
      //chunk 大小警告的限制
      chunkSizeWarningLimit: 800,
      terserOptions: {
        compress: {
          // warnings: false,
          passes: 1,// 控制压缩遍数
          drop_console: true,  //打包时删除console
          drop_debugger: true, //打包时删除 debugger
          pure_funcs: ['console.log'],
        },
        output: {
          // 去掉注释内容
          comments: true,
        },
      },
      // rollupOptions,
      //默认情况下，若 outDir 在 root 目录下，则 Vite 会在构建时清空该目录。
      rollupOptions: {
        output: {
          manualChunks(id) {
            //创建一个vendor包含所有依赖项的块node_modules
            if (id.includes('node_modules')) {
              return 'vendor';
            }
          }
        }
      }
    },
    esbuild,
    optimizeDeps,
    plugins: [
      // legacyPlugin({
      //   targets: ['Android > 39', 'Chrome >= 60', 'Safari >= 10.1', 'iOS >= 10.3', 'Firefox >= 54', 'Edge >= 15'],
      // }), [Banner(`\n guangdong-vue-admin \n Time : ${timestamp}`)],
      vuePlugin(),
      viteCompression({
        verbose: true,
        disable: false,
        threshold: 10240, // 对大于 100kb 的文件进行压缩
        deleteOriginFile: false, // 压缩后是否删除原文件，默认为 false
        filter: '/.(js|mjs|json|css)$/i'
      }),
      visualizer()
    ],
    css: {
      preprocessorOptions: {
        less: {
          // 支持内联 JavaScript
          javascriptEnabled: true,
        },
        scss: {
          charset: false // 关闭sass的@charset输出,去除打包scss警告
        }
      },
      postcss: {
        plugins: [
          {
            postcssPlugin: 'internal:charset-removal',
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === 'charset') {
                  atRule.remove();
                }
              }
            }
          }
        ],
      },
    },
  }
}
